﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using MapControl;

namespace GPSMap
{
    
    public partial class frmGPSMap : Form
    {

        private DataTable dbTestGPS;
        private MapControl.ucMap_2 mapControl;
        //*****************************************************
        //Draw grid to create 9x9 Coordinate
        private Coordinate9x9 _coord9x9;
        private bool isShowCoord9x9 = false;
        private bool isStartTestGPSData = false;
        private GPSPoint currGPSData;

        public frmGPSMap()
        {
            InitializeComponent();
            //Load Map            
            mapControl = new ucMap_2();
            panelMap.Controls.Add(mapControl);
            mapControl.Dock = DockStyle.Fill;
            InitTestGPSData();
        }

        private void frmGPSMap_Load(object sender, EventArgs e)
        {
            _coord9x9 = new Coordinate9x9(mapControl.Map);

            //AddDemoData();
            string[] bigSquareArray = new string[10];// { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            bigSquareArray[0] = txtBigSquare1.Text;
            bigSquareArray[1] = txtBigSquare2.Text;
            bigSquareArray[2] = txtBigSquare3.Text;
            bigSquareArray[3] = txtBigSquare4.Text;
            bigSquareArray[4] = txtBigSquare5.Text;
            bigSquareArray[5] = txtBigSquare6.Text;
            bigSquareArray[6] = txtBigSquare7.Text;
            bigSquareArray[7] = txtBigSquare8.Text;
            bigSquareArray[8] = txtBigSquare9.Text;
            bigSquareArray[9] = txtBigSquare10.Text;
            _coord9x9.BigSquareArray = bigSquareArray;

            ToolStripSetup();
            
        }


        public void ToolStripSetup()
        {
            //// Create the ImageList
            ImageList imgList = new ImageList();
            imgList.ImageSize = new Size(18, 16);
            imgList.ColorDepth = ColorDepth.Depth4Bit;
            imgList.TransparentColor = Color.FromArgb(192, 192, 192);

            // adds the bitmap
            if (File.Exists("buttons.bmp"))
            {
                //path = System.IO.Path.GetFullPath("buttons.bmp");
                //bmp = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream(this.GetType(), "buttons.bmp"));
                Bitmap bmp = new Bitmap("buttons.bmp");
                imgList.Images.AddStrip(bmp);
            }

            toolStripButtonSelectTool.Image = imgList.Images[9];
            toolStripButtonPanTool.Image = imgList.Images[18];
            toolStripButtonZoomIn.Image = imgList.Images[15];
            toolStripButtonZoomOut.Image = imgList.Images[16];
        }

        public void UpdateToolStrip(float x, float y)
        {
            PointF pScreenF = new PointF(x, y);
            //Hiển thị tọa độ Longitude, Latitude
            double lon, lat;
            lon = lat = 0;
            mapControl.Map.ConvertCoord(ref x, ref y, ref lon, ref lat, MapXLib.ConversionConstants.miScreenToMap);
            toolStripStatusLabelCoordinate.Text = string.Format("Lon: {0} - Lat: {1} - Alt: {2}", lon.ToString(), lat.ToString(), mapControl.Map.Zoom.ToString());
            toolStripStatusLabelCoord9x9.Text = string.Format("9x9:{0}", _coord9x9.GetCoordinate(pScreenF));
        }

        private void btnLayers_Click(object sender, EventArgs e)
        {
            if (mapControl.Map.Layers.LayersDlg(null,null))
            {
                
            }
        }

        private void btnSaveGeoSet_Click(object sender, EventArgs e)
        {
            mapControl.Map.Layers.Remove("Symbols");
            mapControl.Map.SaveMapAsGeoset("BanDo", "E:\\Temp\\bando.gst");
            mapControl.Map.Layers.AddUserDrawLayer("Symbols", 1);
        }

        
        private void InitTestGPSData()
        {
            mapControl.AxMap_MouseDownEvent += new AxMapXLib.CMapXEvents_MouseDownEventHandler(AxMap_MouseDownEvent);
            mapControl.AxMap_MouseMoveEvent += new AxMapXLib.CMapXEvents_MouseMoveEventHandler(AxMap_MouseMoveEvent);
            mapControl.AxMap_DrawUserLayer += new AxMapXLib.CMapXEvents_DrawUserLayerEventHandler(AxMap_DrawUserLayer);
            
            
            dbTestGPS = new DataTable();
            dbTestGPS.Columns.Add("LocalTime", typeof(string));
            dbTestGPS.Columns.Add("Name", typeof (string));
            dbTestGPS.Columns.Add("Lon", typeof(string));
            dbTestGPS.Columns.Add("Lat", typeof(string));
            dbTestGPS.Columns.Add("Alt", typeof(string));
            dbTestGPS.Columns.Add("Speed", typeof(string));
            dbTestGPS.Columns.Add("Angle", typeof(string));
            dataGridViewTestGPSData.DataSource = dbTestGPS;

        }
        
        private void btnTest_Click(object sender, EventArgs e)
        {
            isStartTestGPSData = !isStartTestGPSData;
            if (isStartTestGPSData)
            {
                btnTestGPSData.Text = "Stop Test";
            }
            else
            {
                btnTestGPSData.Text = "Start Test";
            }
        }


        public void AxMap_MouseDownEvent(object sender, AxMapXLib.CMapXEvents_MouseDownEvent e)
        {
            PointF pScreen = new PointF(e.x, e.y);
            if (e.button == 1)
            {
                //Nếu là đang thêm dữ liệu mới
                if (isStartTestGPSData)
                {
                    mapControl.Map.CurrentTool = MapXLib.ToolConstants.miArrowTool;
                    
                    //Hiển thị tọa độ Longitude, Latitude
                    double lon, lat;
                    lon = lat = 0;
                    mapControl.Map.ConvertCoord(ref e.x, ref e.y, ref lon, ref lat, MapXLib.ConversionConstants.miScreenToMap);
                    
                    DataRow row = dbTestGPS.NewRow();
                    Random ran = new Random();
                    row.ItemArray = new object[] { DateTime.Now.ToString(), "Heli1", lon.ToString(), lat.ToString(), ran.Next(2000, 3000).ToString(), ran.Next(200, 400).ToString(), ran.Next(0, 360).ToString() };
                    dbTestGPS.Rows.Add(row);
                    mapControl.Map.Refresh();
                }
                else //Nếu đang chọn xem thông tin gps data
                {
                    foreach (DataGridViewRow row in dataGridViewTestGPSData.Rows)
                    {
                        GPSPoint objGPS = GetGPSData(row);
                        //Nếu click trúng vào vị trí GPS thì hiển thị form
                        if (objGPS.HitTest(pScreen) == 0 && 
                            mapControl.Map.CurrentTool == MapXLib.ToolConstants.miArrowTool)
                        {
                            row.Selected = true;
                            currGPSData = objGPS;
                            mapControl.Refresh();
                            string result = string.Format("Name={0}\nLongitude={1}\nLatitude={2}\nAltitude={3}\nSpeed={4}\nAngle={5}",
                                objGPS.Name,
                                objGPS.LonGPS.ToString(),
                                objGPS.LatGPS.ToString(),
                                objGPS.Alt.ToString(),
                                objGPS.Speed.ToString(),
                                objGPS.Angle.ToString()
                                );
                            MessageBox.Show(result);
                        }
                    }

                }
            }
        }

        
        public void AxMap_MouseMoveEvent(object sender, AxMapXLib.CMapXEvents_MouseMoveEvent e)
        {
            UpdateToolStrip(e.x, e.y);
        }

        private void AxMap_MouseWheelEvent(object sender, AxMapXLib.CMapXEvents_MouseWheelEvent e)
        {
            
        }

        public GPSPoint GetGPSData(DataGridViewRow row)
        {
            string name = row.Cells["Name"].Value.ToString();
            DateTime localTime = DateTime.Parse(row.Cells["LocalTime"].Value.ToString());
            double lon = double.Parse(row.Cells["Lon"].Value.ToString());
            double lat = double.Parse(row.Cells["Lat"].Value.ToString());
            double alt = double.Parse(row.Cells["Alt"].Value.ToString());
            double speed = double.Parse(row.Cells["Speed"].Value.ToString());
            double angle = double.Parse(row.Cells["Angle"].Value.ToString());
            GPSPoint obj = new GPSPoint(mapControl.Map, name, localTime, lon, lat, alt, speed, angle);
            
            return obj;
        }

        public void AxMap_DrawUserLayer(object sender, AxMapXLib.CMapXEvents_DrawUserLayerEvent e)
        {
            Graphics g = Graphics.FromHdc(new IntPtr(e.hOutputDC));
            foreach (DataGridViewRow row in dataGridViewTestGPSData.Rows)
            {
               GPSPoint gpsdata = GetGPSData(row);
               gpsdata.Draw(g, Color.Blue);
            }

            if (currGPSData != null)
            {
                currGPSData.Draw(g,Color.Red);
            }

            //9x9 coordinate
            _coord9x9.Init();
            if (isShowCoord9x9)
                _coord9x9.Draw(g);
        }

        
        private void dataGridViewTestGPSData_SelectionChanged(object sender, EventArgs e)
        {
            //Nếu không phải đang tạo dữ liệu test
            if (!isStartTestGPSData)
            {
                if (dataGridViewTestGPSData.CurrentRow != null)
                {
                    currGPSData = GetGPSData(dataGridViewTestGPSData.CurrentRow);
                    mapControl.Map.ZoomTo(mapControl.Map.Zoom, currGPSData.LonGPS, currGPSData.LatGPS);
                    mapControl.Map.Refresh();
                }
            }
        }

        
        private void btnGrid9x9_Click(object sender, EventArgs e)
        {
            isShowCoord9x9 = !isShowCoord9x9;
            mapControl.Refresh();
        }

        private void btnLopBanDo_Click(object sender, EventArgs e)
        {
            if (mapControl.Map.Layers.LayersDlg(null, null))
            {

            }
        }

        private void btnDiaDanh_Click(object sender, EventArgs e)
        {

        }

        private void btnTestGPSData_Click(object sender, EventArgs e)
        {
            isStartTestGPSData = !isStartTestGPSData;
            if (isStartTestGPSData)
            {
                btnTestGPSData.Text = "Stop Test";
            }
            else
            {
                btnTestGPSData.Text = "Start Test";
            }
        }

        private void btnSelectProjections_Click(object sender, EventArgs e)
        {
            mapControl.Map.DisplayCoordSys.PickCoordSys(null, null);
            mapControl.Map.NumericCoordSys = mapControl.Map.DisplayCoordSys; 
        }

        private void txtBigSquare3_TextChanged(object sender, EventArgs e)
        {

        }

        private void toolStripButtonSelectTool_Click(object sender, EventArgs e)
        {
            mapControl.Map.CurrentTool = MapXLib.ToolConstants.miArrowTool;
        }

        private void toolStripButtonPanTool_Click(object sender, EventArgs e)
        {
            mapControl.Map.CurrentTool = MapXLib.ToolConstants.miPanTool;
        }

        private void toolStripButtonZoomIn_Click(object sender, EventArgs e)
        {
            mapControl.Map.CurrentTool = MapXLib.ToolConstants.miZoomInTool;
        }

        private void toolStripButtonZoomOut_Click(object sender, EventArgs e)
        {
            mapControl.Map.CurrentTool = MapXLib.ToolConstants.miZoomOutTool;
        }
    }
}